import React, { useState, useEffect } from "react";
import { Link, Outlet, useNavigate } from "react-router-dom";
import "./Layout.css";

export default function Layout() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userInfo, setUserInfo] = useState({ name: "" });
  const [userRole, setUserRole] = useState("");
  const [roleLoading, setRoleLoading] = useState(true);
  const navigate = useNavigate();

  // 从localStorage获取登录状态和用户信息
  useEffect(() => {
    // 监听localStorage变化
    const handleStorageChange = () => {
      const storedUserInfo = localStorage.getItem("userInfo");
      updateUserState(storedUserInfo);
    };

    // 初始加载
    const storedUserInfo = localStorage.getItem("userInfo");
    updateUserState(storedUserInfo);

    // 添加事件监听器
    window.addEventListener("storage", handleStorageChange);

    // 清理函数
    return () => {
      window.removeEventListener("storage", handleStorageChange);
    };
  }, []);

  // 更新用户状态的辅助函数
  const updateUserState = (storedUserInfo) => {
    if (storedUserInfo) {
      try {
        const parsedUserInfo = JSON.parse(storedUserInfo);
        const userData = {
          ...parsedUserInfo,
          username: parsedUserInfo.username || parsedUserInfo.name || "",
        };
        setUserInfo(userData);
        setIsLoggedIn(true);
        fetchUserRole(userData.username);
      } catch (error) {
        const username = storedUserInfo;
        setUserInfo({ username });
        setIsLoggedIn(true);
        fetchUserRole(username);
      }
    } else {
      setIsLoggedIn(false);
      setUserInfo({ name: "" });
      setUserRole("");
      setRoleLoading(false);
    }
  };

  // 获取用户角色
  // 修改获取用户角色的函数
  const fetchUserRole = (username) => {
    setRoleLoading(true);
    fetch("http://localhost:8080/api/users/role", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("获取用户角色失败");
        }
        return response.text();
      })
      .then((role) => {
        // 清除可能的空白字符
        const cleanRole = role.trim();
        console.log("获取到的用户角色:", cleanRole);
        setUserRole(cleanRole);
        setRoleLoading(false);
      })
      .catch((error) => {
        console.error("获取用户角色时出错:", error);
        setRoleLoading(false);
      });
  };

  // 退出登录函数
  const handleLogout = () => {
    localStorage.removeItem("userInfo");
    localStorage.removeItem("token");
    setIsLoggedIn(false);
    setUserInfo({ name: "" });
    setUserRole("");
    navigate("/login");
  };

  if (roleLoading && isLoggedIn) {
    return <div className="loading">加载角色权限中...</div>;
  }

  return (
    <div className="app-container">
      {/* 左侧菜单栏 */}
      <aside className="sidebar">
        <div className="sidebar-header">
          <h2>电影院管理系统</h2>
        </div>
        <nav className="menu">
          <ul>
            <li>
              <Link to="/">主页</Link>
              <Link to="/users">查看用户列表</Link>
              <Link to="/movies">查看电影库存</Link>
              {/* 只有超级管理员和店长可以使用电影上架功能 */}
              {(userRole === "ROLE_SUPER_ADMIN" ||
                userRole === "ROLE_STORE_MANAGER" ||
                userRole?.includes("SUPER_ADMIN")) && (
                <Link to="/movies/add">电影上架功能</Link>
              )}
              {/* 只有超级管理员和店长可以添加排片 */}
              {(userRole === "ROLE_SUPER_ADMIN" ||
                userRole === "ROLE_STORE_MANAGER" ||
                userRole?.includes("SUPER_ADMIN")) && (
                <Link to="/schedules/add">添加排片</Link>
              )}
              <Link to="/schedules">获取排片</Link>
              <Link to="/tickets/sales">售卖电影票</Link>
              <Link to="/tickets/view">查看卖票情况</Link>
              {/* 只有超级管理员可以设置用户角色 */}
              {(userRole === "ROLE_SUPER_ADMIN" ||
                userRole?.includes("SUPER_ADMIN")) && (
                <Link to="/users/role/setting">设置用户角色</Link>
              )}
            </li>
            {/* 未来可以添加更多菜单 */}
          </ul>
        </nav>
      </aside>

      {/* 主内容区域 */}
      <main className="main-content">
        {/* 顶部导航栏 */}
        <header className="top-nav">
          <div className="logo">电影院管理系统</div>
          <div className="user-actions">
            {isLoggedIn ? (
              <div className="user-info">
                <span>欢迎，{userInfo.username}！</span>
                <span className="user-role">角色: {userRole || "未设置"}</span>
                <button onClick={handleLogout}>退出</button>
              </div>
            ) : (
              <div className="auth-buttons">
                <Link to="/login">
                  <button>登录</button>
                </Link>
                <Link to="/register">
                  <button>注册</button>
                </Link>
              </div>
            )}
          </div>
        </header>

        {/* 页面内容 */}
        <div className="content">
          <Outlet />
        </div>
      </main>
    </div>
  );
}
